package com.example.tiantian.clock;

import com.example.tiantian.BaseActivity;
import com.example.tiantian.R;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.view.WindowManager;
import android.content.DialogInterface.OnClickListener;

/**
 * ���Ӵ����󵯳��Ľ���
 * 
 * TODO ����߳̿��� һ����û�д���dialog���Զ�������˯һ��
 * 
 * @author Frank
 *
 */
public class AlarmActivity extends BaseActivity implements OnClickListener {
    private final static String INTENT_EXTRA_ALARMTIME = "alarmTime";
    private final static long DELAY_TIME = 30000;

    long alarmTime;
    AlarmManager alarmMgr;
    MediaPlayer player;

    @Override
    protected void init() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);

        setContentView(R.layout.activity_alarm);

        alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        initAudio();
    }

    private void initAudio() {
        player = MediaPlayer.create(this, R.raw.maid_with_the_flaxen_hair);
        player.setLooping(true);
        player.start();
    }

    @Override
    protected void event() {
        new AlertDialog.Builder(this).setTitle(R.string.alarm).setIcon(R.drawable.clock_icon)
                .setPositiveButton(R.string.alarm_close, this).setNegativeButton(R.string.alarm_delay, this).show();
    }

    @Override
    protected void loadData() {
        alarmTime = getIntent().getLongExtra(INTENT_EXTRA_ALARMTIME, System.currentTimeMillis());
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        if (which == Dialog.BUTTON_NEGATIVE) {
            Intent intent = new Intent(this, AlarmActivity.class);
            intent.putExtra(INTENT_EXTRA_ALARMTIME, alarmTime + DELAY_TIME);
            PendingIntent operation = PendingIntent.getActivity(this, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            alarmMgr.set(AlarmManager.RTC_WAKEUP, alarmTime + DELAY_TIME, operation);
        }
        finish();
    }

    @Override
    protected void onDestroy() {
        if (player != null) {
            player.stop();
            player.release();
            player = null;
        }
        super.onDestroy();
    }
}
